package com.hlk.hlk_blog.controller;


import com.hlk.hlk_blog.entity.Blog;
import com.hlk.hlk_blog.entity.Excel;
import com.hlk.hlk_blog.entity.User;
import com.hlk.hlk_blog.service.BlogService;
import com.hlk.hlk_blog.service.ExcelService;
import com.hlk.hlk_blog.util.IDUtils;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
public class ExcelController {
    @Autowired
    private ExcelService excelService;
    @Autowired
    private BlogService blogService;

    @GetMapping("/blog/{id}/excel")
    public void download(@PathVariable Long id, HttpServletResponse response) throws IOException {
        Excel excel = excelService.excelall(id);
        //创建excel表单
        XSSFWorkbook workbook = new XSSFWorkbook();
        //设置参数为sheet的名字
        XSSFSheet sheet = workbook.createSheet("Sheet1");
        //创建表头
        setTitle(workbook, sheet);
        //新增数据行，并且设置单元格数据
        int rowNum = 1;
        XSSFRow row = sheet.createRow(rowNum);
        row.createCell(0).setCellValue(excel.getTitle());
        row.createCell(1).setCellValue(excel.getTypeName());
        row.createCell(2).setCellValue(excel.getFlag());
        row.createCell(3).setCellValue(excel.getContent());
        row.createCell(4).setCellValue(excel.getDescription());
        row.createCell(5).setCellValue(excel.getNickname());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createtime = format.format(excel.getCreateTime());
        String updatetime = format.format(excel.getUpdateTime());
        row.createCell(6).setCellValue(createtime);
        row.createCell(7).setCellValue(updatetime);
        String fileName = excel.getId() + "博客" + ".xlsx";
        //清空response
        response.reset();
        //设置response的Header
        response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
        OutputStream os = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/x-download");
        //解决中文乱码
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "iso8859-1"));

        //将excel写入到输出流中
        workbook.write(os);
        os.flush();
        os.close();
    }

    /**
     * 设置表头
     */
    public void setTitle(XSSFWorkbook workbook, XSSFSheet sheet) {
        XSSFRow row = sheet.createRow(0);
        //设置列宽，setColumnWidth的第二个参数要乘以256，这个参数的单位是1/256个字符宽度
        sheet.setColumnWidth(0, 10 * 256);
        sheet.setColumnWidth(1, 20 * 256);
        sheet.setColumnWidth(2, 20 * 256);
        sheet.setColumnWidth(3, 50 * 256);
        sheet.setColumnWidth(4, 20 * 256);
        sheet.setColumnWidth(5, 20 * 256);
        sheet.setColumnWidth(6, 20 * 256);
        sheet.setColumnWidth(7, 20 * 256);
        sheet.setColumnWidth(8, 20 * 256);
        //设置为居中加粗
        XSSFCellStyle style = workbook.createCellStyle();
        //自动换行
        style.setWrapText(true);
        XSSFFont font = workbook.createFont();
        font.setBold(true);
        style.setFont(font);

        XSSFCell cell;
        cell = row.createCell(0);
        cell.setCellValue("标题");
        cell.setCellStyle(style);

        cell = row.createCell(1);
        cell.setCellValue("分类名称");
        cell.setCellStyle(style);

        cell = row.createCell(2);
        cell.setCellValue("标记");
        cell.setCellStyle(style);

        cell = row.createCell(3);
        cell.setCellValue("内容");
        cell.setCellStyle(style);

        cell = row.createCell(4);
        cell.setCellValue("描述");
        cell.setCellStyle(style);

        cell = row.createCell(5);
        cell.setCellValue("作者");
        cell.setCellStyle(style);

        cell = row.createCell(6);
        cell.setCellValue("创建时间");
        cell.setCellStyle(style);

        cell = row.createCell(7);
        cell.setCellValue("更新时间");
        cell.setCellStyle(style);
    }

    @PostMapping("/blog/Excel")
    @ResponseBody
    public String excel(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse
            response, HttpSession session) {
        String filename = file.getOriginalFilename();
        System.out.println(filename);
        String s = filename.substring(filename.indexOf(".") + 1);
        if ("xsl".equals(s) || "xlsx".equals(s)) {
            try {
                // @RequestParam("file") MultipartFile file 是用来接收前端传递过来的文件
                // 1.创建workbook对象，读取整个文档
                InputStream inputStream = file.getInputStream();
                //POIFSFileSystem poifsFileSystem = new POIFSFileSystem(inputStream);
                XSSFWorkbook wb = new XSSFWorkbook(inputStream);
                // 2.读取页脚sheet
                XSSFSheet sheetAt = wb.getSheetAt(0);
                // 3.循环读取某一行
                int index = 0;
                for (Row row : sheetAt) {
                    // 4.读取每一行的单元格
                    if (index == 0) {
                        index++;
                        continue;
                    }
                    /**获取单元格
                     XSSFCell cell = row.getCell(0);
                     设置单元格类型
                     cell.setCellType(CellType.STRING);
                     获取单元格数据
                     String cellValue = cell.getStringCellValue();
                     因为学号是数字，Excel默认是数字类型，我的数据库是字符串类型，所以需要设置下类型
                     row.getCell(1).setCellType(CellType.STRING);*/
                    Blog blog = new Blog();
                    blog.setId(Long.parseLong(IDUtils.createID()));
                    row.getCell(0).setCellType(CellType.STRING);
                    blog.setTitle(row.getCell(0).getStringCellValue());
                    row.getCell(1).setCellType(CellType.STRING);
                    blog.setContent(row.getCell(1).getStringCellValue());
                    row.getCell(2).setCellType(CellType.STRING);
                    blog.setFlag(row.getCell(2).getStringCellValue());
                    blog.setViews(0);
                    blog.setCreateTime(new Date());
                    blog.setUpdateTime(new Date());
                    row.getCell(3).setCellType(CellType.STRING);
                    blog.setDescription(row.getCell(3).getStringCellValue());
                    User user = (User) session.getAttribute("user");
                    blog.setUserId(user.getId());
                    blogService.saveBlog(blog);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "上传成功";
        }
        return "文件格式不符";
    }

}
